package com.uu.it.tracker.computation;

import java.io.IOException;

import com.uu.it.tracker.sensordata.SensorInformer;
import com.uu.it.tracker.sensordata.SensorReader;
import com.uu.it.tracker.views.RunView;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

public class CalculationRunable implements Runnable{
	
	/**
	 * Obtain the handler of interface thread
	 * */
	private Handler _handler;
	
	/**
	 * Key for the status data in the bundle
	 * */
	public final static String key = "SPORTSTATUS";
	
	public CalculationRunable(Handler handler) {
		_handler = handler;
	}
	/**
	 * calculate out suitable result
	 * */
	public void run() {
		/*Generate a sensor informer*/
		SensorInformer sensorInformer = new SensorInformer();
		//Log.i("start informer", "start informer");
		/*Start session*/
		sensorInformer.startSession();
		//Log.i("start session", "start session");
		
		/*Generate a sensor reader*/
		SensorReader sensorReader = new SensorReader();
		/*Open input stream from sensor*/
		sensorReader.start();
		
		/*Generate a calculator*/
		Calculator calculator = new Calculator();
		
		/* Read data from the sensor
		 * Finished when 
		 * */
		while(!(RunView.isFinished)){
			try {
				//read a piece of data from sensor
				TrackerData trackerData = sensorReader.read();
				
				if(trackerData == null) continue;

				//Log.i("SensorData: ", trackerData.toString());

				Calculator.SportStatus sportStatus = calculator.processData(trackerData);
				if(sportStatus != null) {
					//Log.i("SportStatus: ", sportStatus.toString());
					//Update the interface once get a result
					Bundle bundle = new Bundle();
					bundle.putParcelable(key, sportStatus);
					Message message = Message.obtain();
					message.setData(bundle);
					_handler.sendMessage(message);
					}
			}catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		/**
		 * close the input stream to the sensor
		 * */
		sensorReader.close();
		
		/**
		 * close the session
		 * */
		sensorInformer.endSession();
	}
}
